var CURRENT_DESKTOP_ID = 0;
var CURRENT_DESKTOP_NAME = '';
var CONTACT_DETAIL_WINDOW_ID=null;
var EXPLORER_WINDOW_ID=null;
var CONTACT_WINDOW_ID=null;

var wgroup = new Ext.WindowGroup();
var windowsGroup = new Ext.WindowGroup();
  windowsGroup.zseed = 1500000;


/**
 * MAP对象，模拟java.util.MAP功能
 *
 * 接口：
 * size()     获取MAP元素个数
 * isEmpty()    判断MAP是否为空
 * clear()     删除MAP所有元素
 * put(key, value)   向MAP中增加元素（key, value)
 * remove(key)    删除指定KEY的元素，成功返回True，失败返回False
 * get(key)    获取指定KEY的元素值VALUE，失败返回NULL
 * containsKey(key)  判断MAP中是否含有指定KEY的元素
 * values()    获取MAP中所有VALUE的数组（ARRAY）
 * keys()     获取MAP中所有KEY的数组（ARRAY）
 * putAll()   追加另一个map
 * entries()  返回MapEntry[]
 *
 * 例子：

 * var map = new Map();
 *
 * map.put("key", "value");
 * var val = map.get("key")
 *
 */
 
MapEntry=function(k,v){
    this.key=k;
    this.value=v;
    this.keyEquals=function(key2){
        if(this.key==key2){
            return true;
        }else{
            return false;
        }
    }
}
Map=function(){
 	this.elements = [];
}
Map.prototype={
    size:function(){
        return this.elements.length;
    },	
    clear:function(){
    	delete this.elements;
        this.elements=new Array();
    },
		isEmpty:function(){
        return (this.elements==null||this.elements.length<=0);
    },    
    put:function(k,v){
        var newEntry=new MapEntry(k,v);
        for(var i=0;i<this.elements.length;i++){
            var entry=this.elements[i];
            if(entry.keyEquals(k)){
                return;
            }
        }
        this.elements.push(newEntry);        
    },
    get:function(k){
        for(var i=0;i<this.elements.length;i++){
            var entry=this.elements[i];
            if(entry.keyEquals(k)){
                return entry.value;
            }
        }
        return null;
    },
	remove:function(k){
        var entryPoped;
        for(var i=0;i<this.elements.length;i++){
            entryPoped=this.elements.pop();
            if(entryPoped.keyEquals(k)){
                break;
            }else{
                this.elements.unshift(entryPoped);
            }
        }
    },
    keys:function(){
        var keys=[];
        for(var i=0;i<this.elements.length;i++){
            keys.push(this.elements[i].key);
        }
        return keys;
    },
    values:function(){
        var values=[];
        for(var i=0;i<this.elements.length;i++){
            values.push(this.elements[i].value);
        }
        return values;
    },
    containsKey:function(k){
        for(var i=0;i<this.elements.length;i++){
            if(this.elements[i].keyEquals(k))
                return true;
        }
        return false;
    },
    putAll:function(map){
        if(map==null||typeof map!="object"|| !(map instanceof Map)){
            throw new Error("the object to be put should be a valid map");
        }
        for(var i=0;i<map.size();i++){
            this.put(map.elements[i].key,map.elements[i].value);
        }
    },
    entries:function(){
    	return this.elements;
    }
};
/**
 * Javascript中字符串拼接(+)也有性能问题，利用Array.join可提高性能
 * StringBuffer对象,模拟java中的StringBuffer.
 *  
 * 示例： 
 *  var sb=new StringBuffer();
 *  sb.append("aaa").append(100);
 *  alert(sb.toString());
 */
StringBuffer=function(){
	this.elements =[];
}
StringBuffer.prototype={
	append:function(o){
		this.elements[this.elements.length]=o;
		return this;
	},
	toString:function(){
		return this.elements.join("");
	}
}




/**
 *  定义一个全局的Map 模拟SESSION 
 */
var session = new Map();

/**
 * 重写 Ext.MessageBox的alert方法，把按钮由“ok”改成“确定”。
 */
Ext.apply(Ext.MessageBox, {
        alert : function(title, msg, fn, scope){
            this.show({
                title : title,
                msg : msg,
                buttons : {ok:'确定'},
                fn: fn,
                scope : scope,
                minWidth: this.minWidth
            });
            return this;
        }
});

/**
 * 重写 Ext.MessageBox的confirm方法，把按钮由"yes","no"改成“是”，“否”。
 */
Ext.apply(Ext.MessageBox, {
        confirm : function(title, msg, fn, scope){
            this.show({
                title : title,
                msg : msg,
                buttons: {yes:'是',no:'否'},
                fn: fn,
                scope : scope,
                icon: this.QUESTION,
                minWidth: this.minWidth
            });
            return this;
        }
});


Ext.override(Ext.Toolbar, {
				clear : function() {
					var _this = this;
					var _items = _this.items;
					for (var i = 0; i < _items.length; i++) {
						var _key = _items.keys[i];
						if (_key === 'data_count_id') {
							var _obj = _items.get(_key);
							_obj.destroy();
						};
					}
					_items.clear();
				}
			});

function getWinWidth(){ // returns the width of the browser window
//------------------------------------------------------------------------
	
	if (window.innerWidth){
		return(window.innerWidth);
	}else if (document.documentElement && document.documentElement.clientWidth){
		return(document.documentElement.clientWidth);
	}else if (document.body&&document.body.clientWidth){
		
		return(document.body.clientWidth);
	}else {
		return(screen.width);
	}
}
//------------------------------------------------------------------------
function getWinHeight(){ // returns the height of the browser window
//------------------------------------------------------------------------

	if (window.innerHeight){	
	
		return(window.innerHeight);
	}else if (document.documentElement && document.documentElement.clientHeight){

		return(document.documentElement.clientHeight);
	}else if (document.body&&document.body.clientHeight){	
   
		return(document.body.clientHeight);
	}else {
//		alert(4);
		return (window.screen.height);
	}
}
function getRandNumber(){
	var date = new Date();
	var rand = Math.random();
	var returnNumber=date.getTime()*rand;
	return returnNumber.toString();;
}

var LEFT_WINDOW_WIDTH=getWinWidth()*0.15-35;
var LEFT_WINDOW_HEIGHT=getWinHeight()*0.85-11;

var RIGHT_WINDOW_WIDTH=getWinWidth()*0.85-15;
var RIGHT_WINDOW_HEIGHT=getWinHeight()-120;

var TOP_WINDOW_WIDTH=getWinWidth();
var TOP_WINDOW_HEIGHT=getWinHeight()*0.105;

//alert(getWinHeight());
Global = {
	STD_PORTAL : {
		id : 'std-panel',
		xtype : 'portal'
	},
	BTN_ADDWIN : {
		id : 'add-win'
	},
	BTN_LOCKEDIT : {
		id : 'lock-edit'
	},
	STD_GRID_STORE:{
		id:'grid_store'
	},
	STD_WEST_MENU:{
		id:'westPanel_menu'
	},
	ACTION_TYPE_RELOAD:"reload_menu",
	ACTION_TYPE_ADD:"add",
	ACTION_TYPE_EDIT:"edit",
	ACTION_TYPE_DELETE:"delete"
	,queue:{}
	,queueCapacity:3

	
};




var selectButton;







Arr_NewWin = [];

addToNewWinArray = function($comp) {
	
	for (var i in Arr_NewWin) {
		var _id = Arr_NewWin[i].id;
		if (_id == $comp.id) {
			return false;
		}
	}
	Arr_NewWin.push($comp);
//alert("add comp : " + $comp._o);
	if(typeof($comp._o)!="undefined")
	{
		//alert("comp id : " + $comp._o.id);
		winComps.push($comp._o);
	}

	return true;
}

findExistedWin = function($id) {
	
	for (var i in Arr_NewWin) {
		var _id = Arr_NewWin[i].id;
		if (_id == $id) {
			return true;
			break;
		}
	}
	
	return false;
}

delFromNewWinArray = function($comp) {
	for (var i = 0; i < winComps.length; i++) {
		try {
			var _id = winComps[i].id;
			if (_id == $comp._o.id) {
				winComps.splice(i, 1);
				break;
			}
		} catch (e) {
		}
	}

	for (var i = 0; i < Arr_NewWin.length; i++) {
		var _id = Arr_NewWin[i].id;
		if (_id == $comp.id) {
			Arr_NewWin.splice(i, 1);
			return true;
		}
	}

	return false;
}
destroyAllOfNewWinArray = function() {
	var _length = Arr_NewWin.length;
	for (var i = 0; i <_length; i++) {
		var _id = Arr_NewWin[i].id;
		var o = Ext.getCmp(_id)
		if (o) {
			try {
				o.destroy();
			  
			  Ext.each(Ext.StoreMgr.items,function(store){
			    Ext.StoreMgr.unregister(store);
			    
			    });
				o=null;
			} catch (e) {
				try {
					o.close();
					o=null;
				} catch (e) {
				}
			}
		}
	}
	Arr_NewWin = [];
}

destroyWinArray = function(win) {
	var _length = Arr_NewWin.length;
	var arry = [];
	for (var i = 0; i <_length; i++) {
		var _id = Arr_NewWin[i].id;
		var o = Ext.getCmp(_id)
		if (o && o.id != win.id) {
			try {
				o.destroy();
				 Ext.each(Ext.StoreMgr.items,function(store){
			    Ext.StoreMgr.unregister(store);
			    
			    });
				o=null;
			} catch (e) {
				try {
					o.close();
					o=null;
				} catch (e) {
				}
			}
		} else if (o && o.id == win.id) {
			arry.push(o);
		}
	}
	Arr_NewWin = arry;
}


  SyncAjax = function($url,$postData) {
    function createXhrObject() {
        var http;
        var activeX = ['MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];

        try {
            http = new XMLHttpRequest();
        } catch (e) {
            for (var i = 0; i < activeX.length; ++i) {
                try {
                    http = new ActiveXObject(activeX[i]);
                    break;
                } catch (e) { }
            }
        } finally {
            return http;
        }
    };

    var conn = createXhrObject();
//    conn.setRequestHeader("Content-Type","text/html; charset:UTF-8"); 
    var params="";
    var _url=$url;
//alert($postData);
    for(var prop in $postData){
	var param="";
	param=prop.replace(/(^\s+)|(\s+$)/g,"")+"="+$postData[prop].replace(/(^\s+)|(\s+$)/g,"");	
	params=(params=="")?params+param:params+"&"+param;
}
   if(params!=""){
//   	var _params=Ext.encode(params);
    _url=_url.indexOf("?") > -1 ? _url + "&" + params : _url +"?" + params;
   }    
    conn.open("GET", _url, false);
    conn.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); 
    conn.send(null);
    if (conn.responseText != '') {
    	result=Ext.util.JSON.decode(conn.responseText);
    	if(result.failure){
    		Ext.Msg.alert("警告",result.msg);
//    		return;
    	}else{
        return Ext.util.JSON.decode(conn.responseText);
    	 }
    } else {
        return null;
    }
};


 

AjaxDelegate = function($url, $callback, $postdata,$apply,$msg) {
//	alert($url);
	var _url = $url;
	var _callback = $callback;
	var _postdata = $postdata;
	var _arguments = arguments;
	Ext.Ajax.request({
				url : _url,
				params : _postdata,
				method : "POST",
				waitMsg : '正在加载数据',
				success : function($response) {
					//检查session是否过期
			    	checkTimeOut($response);
					var _obj = $response;
					_arguments[1] = _obj;					
					var responseObj=Ext.decode($response.responseText);
					if(responseObj.failure) {
						alertFailure(responseObj);
					}else  {
						if ($apply === 'apply') {//
							_callback.apply(this, _arguments);
						} else if ($apply === 'return') {
							_callback(responseObj);// return
//							Ext.Msg.alert('成功', _data.msg);
							
						} else if (($apply === 'none')) {
							Ext.Msg.alert('提示', responseObj.msg);
							_callback();
						}
					} 
				},
				failure : function($response) {
					var responseObj=Ext.decode($response.responseText);
					Ext.Msg.alert('提示',responseObj.msg);
//					return;
				}
			});
}




var Key_seachText = "";
var KEY_contactsId = null;
var KEY_currComp = null;


var KEY_comp = [];
var addComp = function($comp) {
	KEY_comp.push($comp);
}

var getCompById = function($id){
	for(var i=0;i<KEY_comp.length;i++)
	{
		if( KEY_comp[i].id.indexOf($id)!=-1 )
			return KEY_comp[i];
	}
	return null;
}
var winComps = [];
var addWinComps = function($comp) {
	winComps.push($comp);
}
var updateWinComps = function() {
	for (var i = 0; i < winComps.length; i++) {
		try {
			winComps[i].request();
		} catch (e) {
		}
	}
}

var hideComp = function() {
	for (var i = 0; i < KEY_comp.length; i++) {
		// alert(KEY_comp[i]);
		try {
			if (KEY_comp[i].isVisible()) {
				KEY_comp[i].hide();
			};
		} catch (e) {
		}
	}
}

var createComp = function($id) {
	if ($id.indexOf("rates")>-1) {
		return new CRM.Rates({id:"rates"+getRandNumber()});
	}
	if ($id.indexOf("trades")>-1) {
		return new CRM.Trades({id:"trades"+getRandNumber()});
	}
	if ($id.indexOf("revenues")>-1) {
		return new CRM.Revenues({id:"revenues"+getRandNumber()});
	}
	return null;
}
var fun_toolsClick = function($id) {

	var _bottom = Ext.getCmp(EXPLORER_WINDOW_ID);
	if (_bottom) {
		hideComp();
		var _obj2 = getCompById($id);
		if (_obj2 == null) {
			var comp = createComp($id);
			_bottom.add(comp);
			_bottom.doLayout();
			comp.request();
			addComp(comp);
			KEY_currComp = comp
		} else {
			if (!_obj2.isVisible()) {
				_obj2.show();
			}
			_obj2.request();
			KEY_currComp = _obj2;
		}
	}

	//updateWinComps();
}
var postdata={};
var desktopId = Ext.urlDecode(window.location.search.substring(1)).desktopId;
if(desktopId){
	postdata={
		action:'getTitle',
		desktopId:desktopId
	};
}else{
	postdata={
		action:'getTitle',
		desktopId:''
	};
}



